﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;
using System.Security.Cryptography;
using System.Text;

namespace Site.Secure
{
    public partial class Login : System.Web.UI.Page
    {

        /// <summary>
        /// Generates MD5 hash based on a string input.
        /// Please note this code comes directly from http://blogs.msdn.com/b/csharpfaq/archive/2006/10/09/how-do-i-calculate-a-md5-hash-from-a-string_3f00_.aspx
        /// </summary>
        /// <param name="input">String input of data to be hashed</param>
        /// <returns>128bit MD5 Hash of "input"</returns>
        public string CalculateMD5Hash(string input)
        {
            // step 1, calculate MD5 hash from input
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hash = md5.ComputeHash(inputBytes);

            // step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("x2"));
            }
            return sb.ToString();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {

            string sPassHash = CalculateMD5Hash(edtPass.Text);
            SqlDataSource1.SelectCommand = "SELECT * FROM Users WHERE User_Name='" + edtUser.Text + "' AND Password='" + sPassHash + "'";
            DataSourceSelectArguments Select = new DataSourceSelectArguments();
            DataView View = (DataView)SqlDataSource1.Select(Select);

            if (View.Count == 1) //The User was found and Password is Correct
            {
                try
                {
                    System.Web.Security.FormsAuthentication.SetAuthCookie(View.Table.Rows[0]["User_Name"].ToString(), false);
                    Session["userID"] = edtUser.Text;
                    Session["userType"] = View.Table.Rows[0]["User_Type"].ToString();
                    string Return = Request.QueryString["ReturnUrl"];
                    //Logger.Log("User '" + edtUser.Text + "' Logged On", "LOG ON", Server);
                    if(Return == null)
                    {
                        Response.Redirect("Default.aspx");
                    }
                    else
                    {
                        if(Request.QueryString["ReturnUrl"] == "%2fSecure")
                            Response.Redirect("Default.aspx");
                        else
                        Response.Redirect(Request.QueryString["ReturnUrl"]);
                    }
                }
                catch (HttpException ex)
                {
                    if (ex.ErrorCode == -2147467259) //SSL Error Here
                    {
                        lblStatus.Text = "SSL Error, Can't Login!";
                    }
                }
            }
            else
            {
                lblStatus.Text = "Bad Credentials, Can't Login!";
            }
        }
    }
}